package net.daum.webtoon.android;

import java.util.ArrayList;

import net.daum.webtoon.android.dto.DTO_Page;
import net.daum.webtoon.android.dto.DTO_Result;
import net.daum.webtoon.android.dto.DTO_WebToon;
import net.daum.webtoon.android.io.DaumWebToonsInitTask;
import net.daum.webtoon.android.listener.EndlessScrollListener;
import net.daum.webtoon.android.util.ImageDownloader;
import net.daum.webtoon.android.util.Logger;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import com.example.android.actionbarcompat.BaseActionBarActivity;

public class WebToonAllGridActvity extends BaseActionBarActivity {

	private static final String TAG = WebToonAllGridActvity.class
			.getSimpleName();
	private JSONObject jsonObject;
	private DaumWebToonsInitTask task;

	private int mTotalItemCount = 0;// 총카운트 몇개지??
	private int mWebToonPageNum = 0;// 어떤 페이지서 가져오징??

	private ArrayList<DTO_WebToon> mWebToonList;

	private GridView gridView;
	private WebToonGridAdapter adapter;
	private ProgressBar progressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.actvity_web_toon_all);
		progressBar = (ProgressBar) findViewById(R.id.pb_web_toon);
		gridView = (GridView) findViewById(R.id.gv_web_toon);
		gridView.setOnItemClickListener(new WebToonGridItemClick());
		// 여기 부터 수정함
		mWebToonList = new ArrayList<DTO_WebToon>();
		try {
			jsonObject = new JSONObject(getIntent().getStringExtra("data"));
			mWebToonList = jsonToDtoArray(jsonObject);

		} catch (Exception e) {
			Logger.e(TAG, e.getMessage(), e);
		}
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		if (mWebToonList != null) {
			adapter = new WebToonGridAdapter(WebToonAllGridActvity.this,
					mWebToonList);
			gridView.setAdapter(adapter);
			gridView.setOnScrollListener(new EndlessScrollListener(gridView,
					new EndlessScrollListener.RefreshList() {

						@Override
						public void onRefresh(int pageNumber) {
							System.out.println("aaaaa");
						}
					}));
		}
	}

	@Override
	public void onHomeSelected() {
	}

	@Override
	public void onRefreshSelected(Runnable runnable) {
		task = new DaumWebToonsInitTask(runnable, new RefreshRunnable());
		task.execute(jsonObject);
	}

	@Override
	public void onSearchSelected() {
	}

	@Override
	public void onShareSelected() {
		Intent share = new Intent(Intent.ACTION_SEND);
		share.setType("text/plain");
		share.putExtra(Intent.EXTRA_TEXT,
				"https://play.google.com/store/apps/details?id="
						+ getPackageName());
		startActivity(Intent.createChooser(share,
				getString(R.string.share_apps)));
	}

	private ArrayList<DTO_WebToon> jsonToDtoArray(JSONObject jsonObject)
			throws Exception {
		JSONObject full;
		JSONArray webtoonList;
		DTO_Result lDto_Result;
		DTO_Page lDto_Page;
		full = jsonObject;
		ArrayList<DTO_WebToon> webToonList = null;

		// 데이터 요청의 결과 값들
		lDto_Result = new DTO_Result(full.getJSONObject("result"));

		// 아이템의 총 카운트 및 기타 정보
		lDto_Page = new DTO_Page(full.getJSONObject("page"));
		// 카운트만 체크할때는 요 걸 요청하면 간단한 전체 정보만 준다.
		// http://cartoon.media.daum.net/data/webtoon/list_by_option?page_size=0

		// 실제 웹툰 리스트
		webtoonList = full.getJSONObject("data").getJSONArray("webtoonList");

		mTotalItemCount = Integer.parseInt(lDto_Page.totalItemCount);
		// 결과 성공이고 데이터 가있으면 리스트 추가 시작
		if (lDto_Result.status.equalsIgnoreCase("200") && webtoonList != null
				&& webtoonList.length() > 0) {
			Logger.d(TAG, "리스트 추가 시작");
			// 디비 완성 되면 사용
			// DBProvider.initInstance(getApplicationContext());
			// DBProvider.getInstance().begin();
			webToonList = new ArrayList<DTO_WebToon>();
			for (int i = 0; i < webtoonList.length(); i++) {
				// 실제 웹툰 리스트를 가져와서 하나씩 추가한다.
				JSONObject l_Json_WebToonInfo = webtoonList.getJSONObject(i);
				DTO_WebToon lInfo = new DTO_WebToon(l_Json_WebToonInfo);

				/*
				 * 데이터 내용 대강 요런식임 --------- lInfo.lastTouch 요건 사용가가 웹툰을 읽을 때
				 * System.currentTimeMillis()을 스트링으로 그때그때 넣어주면 됨 필요할까?? 자기가
				 * 읽던거인지 확인하기위해서...?? --------- lInfo.nickname 실제 데이터 요청할때 사용되는
				 * 영어 이름 --------- lInfo.title 제목 --------- 작가는 여러명이 있을수있으므로 대충
				 * 아래와 같은 식으로 가져와야 함 String lString = ""; for (DTO_Artist artist
				 * : info.cartoon.artists) { artist.artistType 요게 picture 이면 그림
				 * 그린놈 아니면 스토리 작가임 lString +=
				 * (artist.artistType.equalsIgnoreCase("picture") ? "그림:" +
				 * artist.penName : "글:" + artist.penName) + "\n"; } ---------
				 * 썸네일 URL이 지들 멋대로 들어있어서 두가지 중에 한가지를 가져와야 함. lThumbUrl = ""; if
				 * (lInfo.thumbnailImage != null) { lThumbUrl =
				 * lInfo.thumbnailImage.url; } else if (lInfo.thumbnailImage2 !=
				 * null) { lThumbUrl = lInfo.thumbnailImage2.url; } --------- 성인
				 * 컨텐츠인지는 이걸로 확인 해야 함 장르 아이디가 array로 되어있음 그중에 99qjsdldlTdmaus
				 * 성인물 boolean isAdult = false; for (DTO_Genre lGenre :
				 * lInfo.cartoon.genres) { if (lGenre.id.equalsIgnoreCase("99"))
				 * isAdult = true; } --------- 연재 중인 컨텐츠 인지는 lInfo.finishYn 요걸로
				 * 확인 Y 면 완결 ---------
				 */

				webToonList.add(lInfo);
			}
			// 디비 완성 되면 사용
			// DBProvider.getInstance().end();
			Logger.d(TAG, "리스트 추가 종료");
		}
		return webToonList;
	}

	private class WebToonGridAdapter extends BaseAdapter {

		private Context context;
		private ArrayList<DTO_WebToon> webToons;
		private LayoutInflater inflater;
		private ImageDownloader downloader = new ImageDownloader();
		private ColorStateList defaultTextColors;

		public WebToonGridAdapter(Context context,
				ArrayList<DTO_WebToon> webToons) {
			this.context = context;
			this.webToons = webToons;
			this.inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return webToons.size();
		}

		@Override
		public Object getItem(int position) {
			return webToons.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.item_web_toon_all,
						parent, false);
				holder.iconView = (ImageView) convertView
						.findViewById(R.id.iv_item_web_toon_selected_thumbnail);
				holder.ageView = (TextView) convertView
						.findViewById(R.id.tv_item_web_toon_selected_age);
				defaultTextColors = holder.ageView.getTextColors();
				holder.titleView = (TextView) convertView
						.findViewById(R.id.tv_item_web_toon_selected_title);
				holder.authorView = (TextView) convertView
						.findViewById(R.id.tv_item_web_toon_selected_author);
				holder.dateView = (TextView) convertView
						.findViewById(R.id.tv_item_web_toon_selected_date);
				holder.ratingView = (RatingBar) convertView
						.findViewById(R.id.rb_item_web_toon_selected_rating);
				holder.ratingView.setMax(10);
				holder.ratingView.setIsIndicator(true);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			DTO_WebToon data = webToons.get(position);
			downloader.download(data.thumbnailImage.url, holder.iconView);
			holder.titleView.setText(data.title);
			setAgeView(holder.ageView, data.ageGrade);
			holder.authorView.setText(data.cartoon.artists.get(0).name);
			holder.dateView.setText(data.dateCreated);
			holder.ratingView.setRating(Float.parseFloat(data.averageScore));
			if (position == webToons.size()) {
				progressBar.setVisibility(View.VISIBLE);
			} else {
				progressBar.setVisibility(View.GONE);
			}
			progressBar.invalidate();
			return convertView;
		}

		private void setAgeView(TextView textView, String age) {
			setAgeView(textView, Integer.parseInt(age));
		}

		private void setAgeView(TextView textView, int age) {
			switch (age) {
			default:
			case 0:
				textView.setText("");
				textView.setTextColor(defaultTextColors);
				break;
			case 19:
				textView.setText(Integer.toString(age));
				textView.setTextColor(Color.RED);
				break;
			}
		}
	}

	private class ViewHolder {
		ImageView iconView;
		TextView ageView;
		TextView titleView;
		TextView authorView;
		TextView dateView;
		RatingBar ratingView;
	}

	private class RefreshRunnable implements Runnable {

		@Override
		public void run() {
			try {
				mWebToonList = jsonToDtoArray(jsonObject);
				adapter = new WebToonGridAdapter(WebToonAllGridActvity.this,
						mWebToonList);
				gridView.setAdapter(adapter);
			} catch (Exception e) {
				Logger.e(TAG, e.getMessage(), e);
			}
		}

	}

	private class WebToonGridItemClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Intent intent = new Intent(WebToonAllGridActvity.this,
					WebToonSelectedListActivity.class);
			intent.putExtra("data", mWebToonList.get(arg2));
			startActivity(intent);
		}

	}
}
